import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author zqc
 * @Date 2021/1/24-16:58
 * @Description HashMap的四种遍历方式
 */
public class HashMapErgodic {

    //① 二次取值(性能差)
    public static void hashMapErgodicOne(Map<Integer, String> map){
        for (int key : map.keySet()) {
            System.out.println("Key: "+key + "\tValue: " + map.get(key));
        }
    }

    //② 一次取值(性能第一种好)
    public static void hashMapErgodicTwo(Map<Integer, String> map){
        Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, String> entry = it.next();
            System.out.println("entry: "+entry+
                    "\nKey: " + entry.getKey() + "\tValue: " + entry.getValue());
        }
    }

    //③ 推荐，尤其是容量大时
    public static void hashMapErgodicThree(Map<Integer, String> map){
        for(Map.Entry<Integer, String> entry : map.entrySet()){
            System.out.println("Key: "+ entry.getKey()+ " Value: "+entry.getValue());
        }
    }

    //④ 遍历所有的value，但不能遍历key
    public static void hashMapErgodicFour(Map<Integer, String> map){
        for(String v : map.values()){
            System.out.println("Value: "+v);
        }
    }

    public static void main(String[] args) {
        //初始化测试数据
        Map<Integer, String> map = new HashMap<>();
        for (int i = 1; i < 5; i++) {
            map.put(i, "map" + i);
        }

        //方法测试
        hashMapErgodicOne(map);
        System.out.println("----------------------");
        hashMapErgodicTwo(map);
        System.out.println("----------------------");
        hashMapErgodicThree(map);
        System.out.println("----------------------");
        hashMapErgodicFour(map);

    }

}
